<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>select2-demo</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <link href="https://cdn.bootcss.com/select2/4.0.3/css/select2.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/select2/4.0.3/js/select2.js"></script>
    <script src="https://cdn.bootcss.com/select2/4.0.3/js/i18n/zh-CN.js"></script>
</head>

<body>
    <h3>本地数据</h3>
    <select name="local-select" id="local-select"></select> <br>
    <h3>ajax获取数据</h3>
    <select name="sel" id="sel"  style="width: 100px;"></select>
    <script type="text/javascript">
        var data = [
            {id: 1, text: 'hahah'},
            {id: 2, text: 'fffff'}
        ]
        //local data
        $('#local-select').select2({
            data: data,
            placeholder: '请选择',
            allowClear: true
        });
        // fetch remote data by ajax
        $("#sel").select2({
            ajax: {
                url: "http://127.0.0.1/select2.php",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    // search term 请求参数 ， 请求框中输入的参数
                    return {
                        q: params.term, // search term
                        page: params.page
                    };
                },
                processResults: function (data, page) {  //ajax result 
                    console.log(data); //data格式{1:'aaa'}
                    return {
                        results: formatData(data)
                    };
                    // return formatData(data);
                },
                cache: true
            },
            minimumInputLength: 1,
            placeholder: '请选择',//默认文字提示
            language: "zh-CN",
            tags: true,//允许手动添加
            allowClear: true,//允许清空
            minimumInputLength: 1//最少输入多少个字符后开始查询
        });
        function formatData (data) {
            // data类型不是对象的话报错
            if (Object.prototype.toString.call(data) !== '[object Object]')  {
                throw new Error('select2 ajax data格式不正确');
            }
            var result = [];
            $.each(data, function(index, value){
                var item = {};
                item.id = index;
                item.text = value;
                result.push(item);
            })
            return result;
        }
        
    </script>
</body>

</html>